import {
    _decorator,
    CCBoolean,
    Component,
    resources,
    Sprite,
    SpriteFrame,
    Collider2D,
    Contact2DType,
    IPhysics2DContact,
    CCInteger,
    Vec3
} from 'cc';
import {PlayerController} from "db://assets/scripts/PlayerController";

const {ccclass, property} = _decorator;

@ccclass('EnemyController')
export class EnemyController extends Component {
    /**
     * 移动速度
     */
    @property(CCInteger)
    speed: number = 300;

    /**
     * 已销毁
     */
    @property(CCBoolean)
    destroyed: boolean = false;

    private collider: Collider2D = null;

    start() {
        // 注册单个碰撞体的回调函数
        this.collider = this.getComponent(Collider2D);
        this.collider?.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
    }

    /**
     * 开始碰撞
     *
     * @param selfCollider 自己
     * @param otherCollider 敌人
     * @param contact 碰撞信息
     */
    onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
        // 当与敌人发送碰撞时
        if (otherCollider.tag === 0) {
            // 销毁敌人
            otherCollider.getComponent(PlayerController).die();
            // 销毁自己
            this.die();
        }
    }

    update(deltaTime: number) {
        // 销毁
        if (this.destroyed) {
            this.node.destroy();
            return;
        }

        // 移动
        this.node.setWorldPosition(new Vec3(this.node.worldPosition.x, this.node.worldPosition.y - this.speed * deltaTime));

        // 屏幕外销毁
        if (this.node.position.y < -850) {
            // 销毁
            this.destroyed = true;
            return;
        }
    }

    /**
     * 销毁
     */
    die() {
        // 当未销毁时
        if (!this.destroyed) {
            // 播放死亡动画
            resources.load("enemy_die/spriteFrame", SpriteFrame, (err: Error, data: SpriteFrame) => {
                if (!err) {
                    this.node.getComponent(Sprite).spriteFrame = data;
                }
            });
            // 延时销毁
            setTimeout(() => {
                // 已销毁
                this.destroyed = true;
            }, 200);
        }
    }
}

